package com.zy.edu.aop;

import com.zy.edu.bean.InputParam;
import com.zy.edu.bean.ResponseInfo;
import com.zy.edu.bean.User;
import com.zy.edu.config.jwt.JwtProperty;
import com.zy.edu.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: HuangHaiShui
 * @description:
 * @date: 2021/7/14 9:22
 * @version: 1.0
 */
//@Aspect
//@Component
public class CheckAop {

    @Resource
    private JwtProperty jwtProperty;
    @Resource
    UserService userService;

    @Pointcut("execution(* com.zy.edu.controller..*.*(..))")
    public void check(){}


    @Around("check()")
    public Object around(ProceedingJoinPoint joinPoint){

        Object result=null;
        try {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method targetMethod = methodSignature.getMethod();
        Object[] args = joinPoint.getArgs();
        HttpServletRequest request = null;

        int index = -1;
        for (int i = 0; i < args.length; i++) {
            Object arg = args[i];
            if (arg instanceof HttpServletRequest) {
                request = (HttpServletRequest) arg;
                index = i;
            }
        }
        if (request == null) {
            System.out.println("request未获取到！");
            return ResponseInfo.error("request未获取到！");
        }
        String url = request.getRequestURI().substring(request.getContextPath().length());
        if (isInclude(url)){
            //如果是属于排除的URL，比如登录，注册，验证码等URL，则直接通行
            return joinPoint.proceed();
        }

        String userId = request.getHeader("userId");
//        String targetUid= request.getHeader("targetUid");
        //检查是否为管理员以及管理员权限
//        boolean check = checkManager(loginUid,targetUid)
//        if(!check){
//            return ResponseInfo.error("request未获取到！");
//        }
            User user = userService.selectById(userId);


            result = joinPoint.proceed();
        }catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return result;
    }

    private boolean isInclude(String url) {
        for (String patternUrl : jwtProperty.getExcludeUrl()) {
            Pattern p = Pattern.compile(patternUrl);
            Matcher m = p.matcher(url);
            if (m.find()) {
                return true;
            }
        }
        return false;
    }
}
